
/***************************************************************/
/*     chaotix_palette.cpp     Functions for MARS palettes     */
/*                             By: Josh Fiorio                 */
/***************************************************************/

#include "chaotix_palette.h"

extern FILE *ROM;           /* TODO: make functions get passed a file argument */
extern int rom_pos;         /* TODO: somehow get passed this to the funcs. as well */
extern long pcolor;         /* TODO: make this get passed to the init function */

void InitPalette(palette &it, long address)
{
    //declare the transparent color
    int transcolor = c256to32(pcolor);
    
    //get the address
    it.address = address;
    
    //goto it's address
    fseek(ROM, it.address, 0);
        rom_pos = it.address;
    
    //get trans color
    it.colors[0] = transcolor;
    
    for (int a=1; a<=96; a++)
	{
        fread(&it.colors[a], sizeof(it.colors[a]), 1, ROM);
            rom_pos = rom_pos + sizeof(it.colors[a]);
			fseek(ROM, rom_pos, 0);

        it.colors[a] = jntohs(it.colors[a]);
    }	//end for
}	//end of func.

void WritePalette(palette &it)
{           
    //go to position of palette
	rom_pos = it.address;
	fseek(ROM, it.address, 0);
    
    for (int lp=1; lp<=15; lp++)
	{
		//get htons of it
		short newCol=0;
		newCol = jhtons(it.colors[lp]);

		//write it to the rom
		fwrite(&newCol, sizeof(newCol), 1, ROM);
			rom_pos = rom_pos + sizeof(newCol);
			fseek(ROM, rom_pos, 0);
    }	//end for
}	//end of func.

long c32to256(short color)
{
	short r,g,b = 0;
	
	//if (color == -1) { return RGB(205,205,205); }
	r = (color & 31) * (255/31);
    g = ((color >> 5) & 31) * (255/31);
    b = ((color >> 10) & 31) * (255/31);

    return RGB(r,g,b);
}	//end of func

short c256to32(long color)
{
	short r,g,b = 0;

	r = (short)ceil((color & 0x000000FF) * (float)31/255);
	g = (short)ceil(((color & 0x0000FF00) >> 8) * (float)31/255);
	b = (short)ceil(((color & 0x00FF0000) >> 16) * (float)31/255);

	g=(g<<5);
	b=(b<<10);

	return r+g+b;
}	//end of func

short GetColorPalette(palette &it, long color)
{
	/*if (!mt)
	{*/
	for (short chk=0; chk<=15; chk++)
	{
		if (c256to32(color) == it.colors[chk])
			return chk;
		//end if
	}	//end for
	/*}
	else
	{
	for (short chk=0; chk<=96; chk++)
	{
		if (c256to32(color) == it.colors[chk])
			return chk;
		//end if
	}	//end for
	}*/

	return 0; //-1
}	//end of func.

